package com.ververica.cdc.guass.sink.jdbc.internal.executor;

import com.ververica.cdc.guass.sink.jdbc.JdbcStatementBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * A {@link JdbcBatchStatementExecutor} that executes supplied statement for given the records
 * (without any pre-processing).
 */
class SimpleBatchStatementExecutor<T> implements JdbcBatchStatementExecutor<T> {

    private static final Logger LOG = LoggerFactory.getLogger(SimpleBatchStatementExecutor.class);

    private final String sql;
    private final JdbcStatementBuilder<T> parameterSetter;
    private final List<T> batch;

    private transient PreparedStatement st;

    SimpleBatchStatementExecutor(String sql, JdbcStatementBuilder<T> statementBuilder) {
        this.sql = sql;
        this.parameterSetter = statementBuilder;
        this.batch = new ArrayList<>();
    }

    @Override
    public void prepareStatements(Connection connection) throws SQLException {
        this.st = connection.prepareStatement(sql);
    }

    @Override
    public void addToBatch(T record) {
        batch.add(record);
    }

    @Override
    public void executeBatch() throws SQLException {
        if (!batch.isEmpty()) {
            try {
                for (T r : batch) {
                    parameterSetter.accept(st, r);
                    st.addBatch();
                }
                st.executeBatch();
            } catch (BatchUpdateException e) {
                handleBatchUpdateException(e);
            } finally {
                batch.clear();
            }
        }
    }

    private void handleBatchUpdateException(BatchUpdateException e) throws BatchUpdateException {
        int[] updateCounts = e.getUpdateCounts();
        for (int i = 0; i < updateCounts.length; i++) {
            if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                handleFailedStatement(batch.get(i));
            }
        }
    }

    private void handleFailedStatement(T record) {
        LOG.error("Failed to execute statement for record: {}", record);
    }

    @Override
    public void closeStatements() throws SQLException {
        if (st != null) {
            st.close();
            st = null;
        }
    }
}